if (typeof(_WEAVER_WEIBO) == "undefined") {
	var _WEAVER_WEIBO = {};
}

_WEAVER_WEIBO.DEBUG = true;
//_WEAVER_WEIBO.DEBUG = false;
_WEAVER_WEIBO.console = Components.classes["@mozilla.org/consoleservice;1"].getService(Components.interfaces.nsIConsoleService);

_WEAVER_WEIBO.debug = function(msg) {
        if (_WEAVER_WEIBO.DEBUG) {
            msg = '[weaver] ' + msg;
            _WEAVER_WEIBO.console.logStringMessage(msg);
        }
};

//////////////////////////////////////////////////////////////////////////////
// global configurations //
_WEAVER_WEIBO.NUM_UPDATED = 500; //number of tweets to be got once
_WEAVER_WEIBO.SLIDESHOW_TIMEOUT = 1000 * 10; //10 seconds interval to slideshow
_WEAVER_WEIBO.REFRESH_TIMEOUT = 2500000; //== NUM_UPDATED * SLIDESHOW_TIMEOUT

_WEAVER_WEIBO.CHECK_UNREAD_TIMEOUT = 30000; //30 seconds interval to check if there's unread msg

_WEAVER_WEIBO.LINE_HEIGHT_SCALE = 0.7;
//////////////////////////////////////////////////////////////////////////////
// global constants //
_WEAVER_WEIBO.HOME_URL = "http://t.sina.com.cn/";
_WEAVER_WEIBO.API_BASE = "http://api.t.sina.com.cn";
//_WEAVER_WEIBO.API_URL = "http://api.t.sina.com.cn/statuses/friends_timeline.json?source=1503290311&count="+_WEAVER_WEIBO.NUM_UPDATED;
_WEAVER_WEIBO.FRIENDS_TIMELINE_API_URL = _WEAVER_WEIBO.API_BASE + "/statuses/friends_timeline.json";
_WEAVER_WEIBO.UPDATE_API_URL = _WEAVER_WEIBO.API_BASE + "/statuses/update.json";
_WEAVER_WEIBO.UNREAD_API_URL = _WEAVER_WEIBO.API_BASE + "/statuses/unread.json";

_WEAVER_WEIBO.PREFs = Components.classes["@mozilla.org/preferences-service;1"].getService(Components.interfaces.nsIPrefService).getBranch("extensions.weaver.weibo.");
_WEAVER_WEIBO.XML_HTTP_REQUEST = Cc["@mozilla.org/xmlextras/xmlhttprequest;1"].createInstance(Ci.nsIXMLHttpRequest);
_WEAVER_WEIBO.XML_HTTP_REQUEST2 = Cc["@mozilla.org/xmlextras/xmlhttprequest;1"].createInstance(Ci.nsIXMLHttpRequest);

//_WEAVER_WEIBO.TIMER = Cc["@mozilla.org/timer;1"].createInstance(Components.interfaces.nsITimer);
_WEAVER_WEIBO.TIMER = {};

_WEAVER_WEIBO.TIMER_ONE_SHOT = Components.interfaces.nsITimer.TYPE_ONE_SHOT;
_WEAVER_WEIBO.TIMER_SLACK_REPEAT = Components.interfaces.nsITimer.TYPE_REPEATING_SLACK;
_WEAVER_WEIBO.WINDOW = Components.classes['@mozilla.org/appshell/window-mediator;1'].getService(Components.interfaces.nsIWindowMediator).getMostRecentWindow('navigator:browser');
_WEAVER_WEIBO.REQUEST_TOKEN_URL = _WEAVER_WEIBO.API_BASE + '/oauth/request_token';
_WEAVER_WEIBO.AUTHORIZE_URL = _WEAVER_WEIBO.API_BASE + '/oauth/authorize';
_WEAVER_WEIBO.ACCESS_TOKEN_URL = _WEAVER_WEIBO.API_BASE + '/oauth/access_token';
//*** keys for app: oplatform
//_WEAVER_WEIBO.CONSUMER_KEY = '501391513';
//_WEAVER_WEIBO.CONSUMER_SEC = 'b04421ac801c0b47f915242c0a6949bf';
//*** keys for app: weaver
_WEAVER_WEIBO.CONSUMER_KEY = '2250519426';
_WEAVER_WEIBO.CONSUMER_SEC = '446de75c7fd45bd28e1906ffdcf0a436';
//////////////////////////////////////////////////////////////////////////////
// global vars //
_WEAVER_WEIBO.request_token = '';
_WEAVER_WEIBO.request_token_secret = '';
_WEAVER_WEIBO.pin = '';
_WEAVER_WEIBO.access_token = '';
_WEAVER_WEIBO.access_token_secret = '';
_WEAVER_WEIBO.tweets = [];
_WEAVER_WEIBO.current_tweet = -1;
_WEAVER_WEIBO.texts = {};
_WEAVER_WEIBO.scroll_enabled = true;
_WEAVER_WEIBO.scroll_buttons = ["start_scroll.png", "stop_scroll.png"];
_WEAVER_WEIBO.enabled = true;
_WEAVER_WEIBO.display = ["none", ""];
//////////////////////////////////////////////////////////////////////////////

_WEAVER_WEIBO.getText = function(key) {
	return _WEAVER_WEIBO.texts["sinaweibo_strings"].getString(key);
};

_WEAVER_WEIBO.scroll = function() {
	_WEAVER_WEIBO.scroll_enabled = !_WEAVER_WEIBO.scroll_enabled;
	image_url = "chrome://sinaweibo/content/images/" + _WEAVER_WEIBO.scroll_buttons[_WEAVER_WEIBO.scroll_enabled&1];
	document.getElementById("scroll-image").setAttribute("src", image_url);
};

_WEAVER_WEIBO.compose_urlparamstr = function(dict) {
	var urlparams = [];
	for (var p in dict) {
		urlparams.push(p + '=' + encodeURIComponent(dict[p]));
	}
	return urlparams.join('&');
};

_WEAVER_WEIBO.asetTimeout = function(name, func, delay) {
    if (_WEAVER_WEIBO.TIMER[name] == null)
        _WEAVER_WEIBO.TIMER[name] = Cc["@mozilla.org/timer;1"].createInstance(Components.interfaces.nsITimer);
	var ev = { notify:function(timer){func();} };
	_WEAVER_WEIBO.TIMER[name].initWithCallback(ev, delay, _WEAVER_WEIBO.TIMER_ONE_SHOT);
};

_WEAVER_WEIBO.compose_urlparamstr = function(dict) {
	var urlparams = [];
	for (var p in dict) {
		urlparams.push(p + '=' + encodeURIComponent(dict[p]));
	}
	return urlparams.join('&');
};

_WEAVER_WEIBO.decompose_urlparamstr = function(str) {
	var params = {};
	var urlparams = str.split('&');
	for (var i in urlparams) {
		var x = urlparams[i].split('=');
		params[x[0]] = x[1];
	}
	return params;
};

_WEAVER_WEIBO.clear_all_children = function(element_id) {
	var element = document.getElementById(element_id);
	while (element.hasChildNodes()) {
		element.removeChild(element.firstChild);
	}
};

_WEAVER_WEIBO.on_general_error = function(msg) {
    //disable timer
	_WEAVER_WEIBO.disable_timer();
	
	_WEAVER_WEIBO.error = true;
	document.getElementById("words-panel").setAttribute("label", msg);

	var retry = document.createElement('label');
	retry.setAttribute('value', _WEAVER_WEIBO.getText("retry"));
	retry.setAttribute('class', 'btn');
	retry.setAttribute('onclick', '_WEAVER_WEIBO.init()');
	document.getElementById('name-quote-panel').appendChild(retry);
};


_WEAVER_WEIBO.on_network_error = function(aEvent) {
	_WEAVER_WEIBO.on_general_error(_WEAVER_WEIBO.getText("connectError")+ " " + aEvent.target.status);
};

_WEAVER_WEIBO.oauth_init = function() {
    _WEAVER_WEIBO.debug("oauth_init()");
	let req = _WEAVER_WEIBO.XML_HTTP_REQUEST;
	req.onerror = _WEAVER_WEIBO.on_network_error;

	var request_token_url = _WEAVER_WEIBO.REQUEST_TOKEN_URL;
	var authorize_url = _WEAVER_WEIBO.AUTHORIZE_URL;
	var access_token_url = _WEAVER_WEIBO.ACCESS_TOKEN_URL;
	var consumer_key = _WEAVER_WEIBO.CONSUMER_KEY;
	var consumer_sec = _WEAVER_WEIBO.CONSUMER_SEC;
	//get request_token
	var message = {action:request_token_url, method:'POST', parameters:[]};
	var accessor = {consumerSecret:consumer_sec,tokenSecret:''};
	message.parameters.push(['oauth_consumer_key', consumer_key]);
	message.parameters.push(['oauth_signature_method', 'HMAC-SHA1']);
	message.parameters.push(['oauth_timestamp', '']);
	message.parameters.push(['oauth_nonce', '']);
	message.parameters.push(['oauth_signature', '']);
	_WEAVER_WEIBO_OAuth.setTimestampAndNonce(message);
	_WEAVER_WEIBO_OAuth.SignatureMethod.sign(message, accessor);
	var paramMap1 = _WEAVER_WEIBO_OAuth.getParameterMap(message.parameters);
	req.onload = 
		function(aEvent) {
			let text = aEvent.target.responseText;
			var p = _WEAVER_WEIBO.decompose_urlparamstr(text);
			if (p['oauth_token']) {
				_WEAVER_WEIBO.request_token = p['oauth_token'];
				_WEAVER_WEIBO.request_token_secret = p['oauth_token_secret'];
				//authorize
				_WEAVER_WEIBO.asetTimeout('oauth_authorize', function(){_WEAVER_WEIBO.oauth_authorize();}, 10);
			} else {
				alert(_WEAVER_WEIBO.getText("requestTolenError"));
			}
		};
	req.open(message.method, message.action, true); //async!
	//don't use sync, otherwise you will freeze firefox while waiting for network response
	var msg = _WEAVER_WEIBO.compose_urlparamstr(paramMap1);
	_WEAVER_WEIBO.send_message(req, msg);
};
_WEAVER_WEIBO.send_message = function(req, msg) {
	req.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
	req.setRequestHeader("Content-length", msg.length);
	req.setRequestHeader("Connection", "close");
	req.send(msg);
};

_WEAVER_WEIBO.oauth_authorize = function() {
	var authorize_url = _WEAVER_WEIBO.AUTHORIZE_URL;
	//get PIN
	var paramMap2 = {};
	paramMap2['oauth_token'] = _WEAVER_WEIBO.request_token;
	paramMap2['oauth_callback'] = '';
	var msg = _WEAVER_WEIBO.compose_urlparamstr(paramMap2);
	var url = authorize_url + '?' + msg;
	var win = _WEAVER_WEIBO.WINDOW;
	win.gBrowser.selectedTab = win.gBrowser.addTab(url);

	_WEAVER_WEIBO.show_interactions();
	
	document.getElementById("name-label").setAttribute("value", _WEAVER_WEIBO.getText("authorizationSuggest"));

	_WEAVER_WEIBO.input_pin = document.createElement('textbox');
	document.getElementById('name-quote-panel').appendChild(_WEAVER_WEIBO.input_pin);
	var submit_pin = document.createElement('label');
	submit_pin.setAttribute('value', _WEAVER_WEIBO.getText("submitPin"));
	submit_pin.setAttribute('class', 'btn');
	submit_pin.setAttribute('onclick', '_WEAVER_WEIBO.oauth_access_token()');
	document.getElementById('name-quote-panel').appendChild(submit_pin);
};

_WEAVER_WEIBO.trim = function(str) {
	return str.replace(/^\s+|\s+$/g,"");
};

_WEAVER_WEIBO.oauth_access_token = function() {
	let req = _WEAVER_WEIBO.XML_HTTP_REQUEST;
	req.onerror = _WEAVER_WEIBO.on_network_error;

	var request_token_url = _WEAVER_WEIBO.REQUEST_TOKEN_URL;
	var authorize_url = _WEAVER_WEIBO.AUTHORIZE_URL;
	var access_token_url = _WEAVER_WEIBO.ACCESS_TOKEN_URL;
	var consumer_key = _WEAVER_WEIBO.CONSUMER_KEY;
	var consumer_sec = _WEAVER_WEIBO.CONSUMER_SEC;
	//get PIN
	var pin = _WEAVER_WEIBO.input_pin.value; //global var _WEAVER_WEIBO.input_pin
	pin = _WEAVER_WEIBO.trim(pin);
	//get access token 
	var message = {action:access_token_url, method:'POST', parameters:[]};
	var accessor = {consumerSecret:consumer_sec,tokenSecret:_WEAVER_WEIBO.request_token_secret};
	message.parameters.push(['oauth_consumer_key', consumer_key]);
	message.parameters.push(['oauth_token', _WEAVER_WEIBO.request_token]);
	message.parameters.push(['oauth_signature_method', 'HMAC-SHA1']);
	message.parameters.push(['oauth_timestamp', '']);
	message.parameters.push(['oauth_nonce', '']);
	message.parameters.push(['oauth_signature', '']);
	message.parameters.push(['oauth_verifier', pin]); //additional req of sina weibo
	_WEAVER_WEIBO_OAuth.setTimestampAndNonce(message);
	_WEAVER_WEIBO_OAuth.SignatureMethod.sign(message, accessor);
	var paramMap1 = _WEAVER_WEIBO_OAuth.getParameterMap(message.parameters);
	req.onload = 
		function(aEvent) {
			let text = aEvent.target.responseText;
			var p = _WEAVER_WEIBO.decompose_urlparamstr(text);
			if (p['oauth_token']) {
				_WEAVER_WEIBO.access_token = p['oauth_token'];
				_WEAVER_WEIBO.access_token_secret = p['oauth_token_secret'];
				//save to pref for future use
				let prefs = _WEAVER_WEIBO.PREFs;
				prefs.setCharPref('sina.oauth.access_token', _WEAVER_WEIBO.access_token);
				prefs.setCharPref('sina.oauth.access_token_secret', _WEAVER_WEIBO.access_token_secret);
				var panel = document.getElementById("name-quote-panel");
				panel.removeChild(panel.lastChild);
				panel.removeChild(panel.lastChild);
				_WEAVER_WEIBO.init_when_loggedin();
			} else {
				alert(_WEAVER_WEIBO.getText("pinError"));
			}
		};

	req.open(message.method, message.action, true); //async!
	var msg = _WEAVER_WEIBO.compose_urlparamstr(paramMap1);
	//headers are very very important!
	_WEAVER_WEIBO.send_message(req, msg);
}

_WEAVER_WEIBO.post_new = function(msg, text) {
	if (msg == null) msg = _WEAVER_WEIBO.getText("updateDialogSugget");
	if (text == null) text = '';

	var newt = window.prompt(msg, text);
	if (newt != null) {
		while (newt.length > 140) {
			newt = window.prompt(_WEAVER_WEIBO.getText("statusTooLong"), newt);
		}
		_WEAVER_WEIBO.do_post(newt);
	}
};

_WEAVER_WEIBO.do_post = function(tweet) {
	let url = _WEAVER_WEIBO.UPDATE_API_URL;
	let req = _WEAVER_WEIBO.XML_HTTP_REQUEST;
	//sign request
	var consumer_key = _WEAVER_WEIBO.CONSUMER_KEY;
	var consumer_sec = _WEAVER_WEIBO.CONSUMER_SEC;
	var message = {action:url, method:'POST', parameters:[]};
	var accessor = {consumerSecret:consumer_sec,tokenSecret:_WEAVER_WEIBO.access_token_secret};
	message.parameters.push(['oauth_consumer_key', consumer_key]);
	message.parameters.push(['oauth_token', _WEAVER_WEIBO.access_token]);
	message.parameters.push(['oauth_signature_method', 'HMAC-SHA1']);
	message.parameters.push(['oauth_timestamp', '']);
	message.parameters.push(['oauth_nonce', '']);
	message.parameters.push(['oauth_signature', '']);
	message.parameters.push(['status', tweet]); //additional param for sina weibo
	_WEAVER_WEIBO_OAuth.setTimestampAndNonce(message);
	_WEAVER_WEIBO_OAuth.SignatureMethod.sign(message, accessor);
	var paramMap1 = _WEAVER_WEIBO_OAuth.getParameterMap(message.parameters);

	req.onload = 
		function(aEvent) {
			let text = aEvent.target.responseText;
			let jsObject = {};
			try {
				jsObject = JSON.parse(text);
			} catch (err) {
				_WEAVER_WEIBO.post_new(_WEAVER_WEIBO.getText("jsonError"), tweet);
				return;
			}

			if (jsObject.error_code == 403) {
				_WEAVER_WEIBO.post_new(_WEAVER_WEIBO.getText("jsonError"), tweet);
				_WEAVER_WEIBO.asetTimeout('oauth_init', function(){_WEAVER_WEIBO.oauth_init();}, 10);
			} else if (jsObject.error_code == 400) {
				_WEAVER_WEIBO.post_new(_WEAVER_WEIBO.getText("statusBlank"), tweet);
			} else {
				alert(_WEAVER_WEIBO.getText("updateSuccess"));
			}
		};

	req.onerror = function(evt) {
		_WEAVER_WEIBO.post_new(_WEAVER_WEIBO.getText("networkError"), tweet);
	}

	req.open(message.method, message.action, true); //async!
	var msg = _WEAVER_WEIBO.compose_urlparamstr(paramMap1);
	_WEAVER_WEIBO.send_message(req, msg);
};

_WEAVER_WEIBO.show_interactions = function() {
	document.getElementById('post-panel').style.display = "block";
	document.getElementById('name-quote-panel').style.display = "block";
	document.getElementById('previous-next-panel').style.display = "block";
};

_WEAVER_WEIBO.hide_interactions = function() {
	document.getElementById('post-panel').style.display = "none";
	document.getElementById('previous-next-panel').style.display = "none";
	_WEAVER_WEIBO.hide_unread();
};

_WEAVER_WEIBO.show_unread = function() {
	document.getElementById('unread-panel').style.display = "block";
};

_WEAVER_WEIBO.hide_unread = function() {
	document.getElementById('unread-panel').style.display = "none";
};

_WEAVER_WEIBO.check_unread = function() {
	_WEAVER_WEIBO.debug('check_unread()');
	let url = _WEAVER_WEIBO.UNREAD_API_URL;
	let req = _WEAVER_WEIBO.XML_HTTP_REQUEST2; //use req 2 to avoid conflict with refresh request
	//sign request
	var consumer_key = _WEAVER_WEIBO.CONSUMER_KEY;
	var consumer_sec = _WEAVER_WEIBO.CONSUMER_SEC;
	var message = {action:url, method:'POST', parameters:[]};
	var accessor = {consumerSecret:consumer_sec,tokenSecret:_WEAVER_WEIBO.access_token_secret};
	message.parameters.push(['oauth_consumer_key', consumer_key]);
	message.parameters.push(['oauth_token', _WEAVER_WEIBO.access_token]);
	message.parameters.push(['oauth_signature_method', 'HMAC-SHA1']);
	message.parameters.push(['oauth_timestamp', '']);
	message.parameters.push(['oauth_nonce', '']);
	message.parameters.push(['oauth_signature', '']);
	_WEAVER_WEIBO_OAuth.setTimestampAndNonce(message);
	_WEAVER_WEIBO_OAuth.SignatureMethod.sign(message, accessor);
	var paramMap1 = _WEAVER_WEIBO_OAuth.getParameterMap(message.parameters);

	req.onload = 
		function(aEvent) {
			let text = aEvent.target.responseText;
			let jsObject = {};
			try {
				jsObject = JSON.parse(text);
			} catch (err) {
				_WEAVER_WEIBO.on_general_error(_WEAVER_WEIBO.getText("jsonError"));
				return;
			}

			if (jsObject.error_code == 403) {
				_WEAVER_WEIBO.asetTimeout('oauth_init', function(){_WEAVER_WEIBO.oauth_init();}, 10);
			} else if (jsObject.comments || jsObject.dm || jsObject.mentions || jsObject.followers) {
				_WEAVER_WEIBO.show_unread();
			} else {
				_WEAVER_WEIBO.hide_unread();
			}
		};

	req.onerror = _WEAVER_WEIBO.on_network_error;

	req.open(message.method, message.action, true); //async!
	var msg = _WEAVER_WEIBO.compose_urlparamstr(paramMap1);
	//headers are very very important!
	_WEAVER_WEIBO.send_message(req, msg);
	_WEAVER_WEIBO.asetTimeout('check_unread', function(){_WEAVER_WEIBO.check_unread();}, _WEAVER_WEIBO.CHECK_UNREAD_TIMEOUT);
};

_WEAVER_WEIBO.refresh = function() {
    _WEAVER_WEIBO.debug("refresh()");
	/****** initialize the bar for estimating content_width *******/
	_WEAVER_WEIBO.show_interactions();
	//calculate size
	/****** clean the bar after estimating content_width *******/
//	_WEAVER_WEIBO.hide_interactions();

	/********* finish initialization *******/
	let url = _WEAVER_WEIBO.FRIENDS_TIMELINE_API_URL;
	let req = _WEAVER_WEIBO.XML_HTTP_REQUEST;
	//sign request
	var consumer_key = _WEAVER_WEIBO.CONSUMER_KEY;
	var consumer_sec = _WEAVER_WEIBO.CONSUMER_SEC;
	var message = {action:url, method:'POST', parameters:[]};
	var accessor = {consumerSecret:consumer_sec,tokenSecret:_WEAVER_WEIBO.access_token_secret};
	message.parameters.push(['oauth_consumer_key', consumer_key]);
	message.parameters.push(['oauth_token', _WEAVER_WEIBO.access_token]);
	message.parameters.push(['oauth_signature_method', 'HMAC-SHA1']);
	message.parameters.push(['oauth_timestamp', '']);
	message.parameters.push(['oauth_nonce', '']);
	message.parameters.push(['oauth_signature', '']);
	message.parameters.push(['count', '200']); //additional param for sina weibo. max 200.
	_WEAVER_WEIBO_OAuth.setTimestampAndNonce(message);
	_WEAVER_WEIBO_OAuth.SignatureMethod.sign(message, accessor);
	var paramMap1 = _WEAVER_WEIBO_OAuth.getParameterMap(message.parameters);

	req.onload = 
		function(aEvent) {
			let text = aEvent.target.responseText;
			//let jsObject = JSON.parse(text);
			let jsObject = {};
			try {
				jsObject = JSON.parse(text);
			} catch (err) {
				_WEAVER_WEIBO.on_general_error(_WEAVER_WEIBO.getText("jsonError"));
				return;
			}

			if (jsObject.error_code == 403) {
				_WEAVER_WEIBO.asetTimeout('oauth_init', function(){_WEAVER_WEIBO.oauth_init();}, 10);
			} else if (jsObject.length) {
				for (var i = 0; i < jsObject.length; i++) {
					let tid = jsObject[i].id;
					let uid = jsObject[i].user.id;
					var t = jsObject[i].text;
					var name = jsObject[i].user.screen_name;
					_WEAVER_WEIBO.tweets.push({'t':t, 'tid':tid, 'uid':uid, 'name': name});
				}

				_WEAVER_WEIBO.asetTimeout('show', function(){_WEAVER_WEIBO.show_interactions(); _WEAVER_WEIBO.show();}, 10);
			} else {
				   document.getElementById("words-panel").setAttribute("label", _WEAVER_WEIBO.getText("requestError")
						   + jsObject.error_code);
			}
		};

	req.onerror = _WEAVER_WEIBO.on_network_error;

	req.open(message.method, message.action, true); //async!
	var msg = _WEAVER_WEIBO.compose_urlparamstr(paramMap1);
	//headers are very very important!
	_WEAVER_WEIBO.send_message(req, msg);
	_WEAVER_WEIBO.asetTimeout('refresh', function(){_WEAVER_WEIBO.refresh();}, _WEAVER_WEIBO.REFRESH_TIMEOUT);
};

_WEAVER_WEIBO.show = function() {
	if (_WEAVER_WEIBO.scroll_enabled) {
		_WEAVER_WEIBO.current_tweet = _WEAVER_WEIBO.current_tweet != _WEAVER_WEIBO.tweets.length
			? ++_WEAVER_WEIBO.current_tweet
					: 0;
		_WEAVER_WEIBO.show_tweet();
	}
	_WEAVER_WEIBO.asetTimeout('show', function(){_WEAVER_WEIBO.show();}, _WEAVER_WEIBO.SLIDESHOW_TIMEOUT);
};

_WEAVER_WEIBO.show_previous = function() {
	_WEAVER_WEIBO.current_tweet = _WEAVER_WEIBO.current_tweet > 0 
		? --_WEAVER_WEIBO.current_tweet 
				: _WEAVER_WEIBO.tweets.length-1;
	_WEAVER_WEIBO.show_tweet();
};

_WEAVER_WEIBO.show_next = function() {
	_WEAVER_WEIBO.current_tweet = _WEAVER_WEIBO.current_tweet < _WEAVER_WEIBO.tweets.length-1 
		? ++_WEAVER_WEIBO.current_tweet 
			: 0;
	_WEAVER_WEIBO.show_tweet();
};

_WEAVER_WEIBO.show_tweet = function() {
	document.getElementById("name-label").setAttribute("value", _WEAVER_WEIBO.tweets[_WEAVER_WEIBO.current_tweet].name);
	document.getElementById("words-panel").setAttribute("label", _WEAVER_WEIBO.tweets[_WEAVER_WEIBO.current_tweet].t);
};

_WEAVER_WEIBO.open_weibo_hp = function() {
	//open sina microblog homepage in a new tab
	var win = Components.classes['@mozilla.org/appshell/window-mediator;1']
		.getService(Components.interfaces.nsIWindowMediator)
		.getMostRecentWindow('navigator:browser');
	win.gBrowser.selectedTab = win.gBrowser.addTab(_WEAVER_WEIBO.HOME_URL);
};

_WEAVER_WEIBO.open_this = function() {
	let weibo = _WEAVER_WEIBO.tweets;
	let i = _WEAVER_WEIBO.current_tweet;
	//open current tweet in a new tab
	var win = Components.classes['@mozilla.org/appshell/window-mediator;1']
		.getService(Components.interfaces.nsIWindowMediator)
		.getMostRecentWindow('navigator:browser');
	win.gBrowser.selectedTab = win.gBrowser.addTab(_WEAVER_WEIBO.API_BASE + '/'
			+ weibo[i].uid + '/statuses/'
			+ weibo[i].tid);
};

_WEAVER_WEIBO.init = function() {
    _WEAVER_WEIBO.debug("init() now");
	let prefs = _WEAVER_WEIBO.PREFs;

	_WEAVER_WEIBO.enable_timer();

	//remove label(which is the retry link)
	if (_WEAVER_WEIBO.error) {
		var name_quote_panel = document.getElementById("name-quote-panel");
		name_quote_panel.removeChild(name_quote_panel.lastChild);
	}
	//load texts
	_WEAVER_WEIBO.texts["sinaweibo_strings"] = document.getElementById("sinaweibo_strings");
	
	document.getElementById("words-panel").setAttribute("label", _WEAVER_WEIBO.getText("loading"));
	
	//register the observer for observing the prefs change
	_WEAVER_WEIBO.PREFs.QueryInterface(Components.interfaces.nsIPrefBranch2);
	_WEAVER_WEIBO.PREFs.addObserver("", this, false);

	//oauth first
	_WEAVER_WEIBO.access_token = prefs.getCharPref('sina.oauth.access_token');
	_WEAVER_WEIBO.access_token_secret = prefs.getCharPref('sina.oauth.access_token_secret');
    _WEAVER_WEIBO.debug("init(): access_token="+_WEAVER_WEIBO.access_token);
	if (_WEAVER_WEIBO.access_token == '') {
		//init oauth
		_WEAVER_WEIBO.asetTimeout('oauth_init', function(){_WEAVER_WEIBO.oauth_init();}, 10);
	} else {
		_WEAVER_WEIBO.init_when_loggedin();
	}
};

_WEAVER_WEIBO.init_when_loggedin = function() {
    _WEAVER_WEIBO.debug("init_when_loggedin()");
	//update & check unread
	_WEAVER_WEIBO.asetTimeout('refresh', function(){_WEAVER_WEIBO.refresh();}, 10);
	_WEAVER_WEIBO.asetTimeout('check_unread', function(){_WEAVER_WEIBO.check_unread();}, 1000); //after 1 sec
};

_WEAVER_WEIBO.destroy = function() {
	_WEAVER_WEIBO.PREFs.removeObserver("", this);
};

_WEAVER_WEIBO.observe = function(subject, topic, data) {
	if (topic != "nsPref:changed")
		return;

    _WEAVER_WEIBO.debug("observed:data="+data);

	switch (data)
	{
		case "sina.oauth.access_token":
		//case "sina.oauth.access_token_secret":
		_WEAVER_WEIBO.access_token = _WEAVER_WEIBO.PREFs.getCharPref('sina.oauth.access_token');
		//_WEAVER_WEIBO.access_token_secret = _WEAVER_WEIBO.PREFs.getCharPref('sina.oauth.access_token_secret');
        _WEAVER_WEIBO.debug("observed:access_token="+_WEAVER_WEIBO.access_token);
		if (_WEAVER_WEIBO.access_token == '')// || _WEAVER_WEIBO.access_token_secret == '')
			_WEAVER_WEIBO.logout();
		break;
	}
};

_WEAVER_WEIBO.disable_timer = function() {
	//clear current timeout
    for (var name in _WEAVER_WEIBO.TIMER)
        _WEAVER_WEIBO.TIMER[name].cancel();
};

_WEAVER_WEIBO.enable_timer = function() {
};

_WEAVER_WEIBO.logout = function() {
    _WEAVER_WEIBO.debug("logout()");
	_WEAVER_WEIBO.disable_timer();

	document.getElementById("words-panel").setAttribute("label", _WEAVER_WEIBO.getText("logoutSuccess"));
	_WEAVER_WEIBO.error = true;

	var reinit = document.createElement('label');
	reinit.setAttribute('value', _WEAVER_WEIBO.getText("login"));
	reinit.setAttribute('class', 'btn');
	reinit.setAttribute('onclick', '_WEAVER_WEIBO.init()');
	document.getElementById('name-quote-panel').appendChild(reinit);
};

_WEAVER_WEIBO.close = function() {
	_WEAVER_WEIBO.enabled = !_WEAVER_WEIBO.enabled;
	document.getElementById("weibo-status").style.display = _WEAVER_WEIBO.display[_WEAVER_WEIBO.enabled&1];
};

//////////////////////////////////////////////////////////////////////////////
// execute _WEAVER_WEIBO.init when ext is being loaded //
// must wait until being loaded otherwise clientWidth will be wrong //
// Should wait further..until window ready. otherwise clientWidth will be wrong.
// -- commented by Evan 2010/9/15 //
window.addEventListener("load", function(e){
        //see: https://wiki.mozilla.org/Performance/Addons/BestPractices#Removing_Event_Listeners
        removeEventListener('load', arguments.callee, true);

		_WEAVER_WEIBO.asetTimeout('init', function(){_WEAVER_WEIBO.init();}, 3000); //FIXME 3 sec is supposed to be long enough to wait for final-ui-startup... XPCOM doc is too shit to read and use
		}, false);

window.addEventListener("unload", function(e){_WEAVER_WEIBO.destroy();}, false);

